﻿package {
	public class MyGeom{
		static function DistanceTriangle(Px:Number,Py:Number,T):Number{
			var x0:Number = T.x0,y0:Number = T.y0;
			var d0u:Number = T.x1 - x0,d0v:Number = T.y1 - y0;
			var d1u:Number = T.x2 - x0,d1v:Number = T.y2 - y0;
			var a00:Number = d0u*d0u+d0v*d0v;
			var a01:Number = d0u*d1u+d0v*d1v;
			var a11:Number = d1u*d1u+d1v*d1v;
			var ypu:Number = Px - x0,ypv:Number = Py - y0;
			var b0:Number = ypu*d0u+ypv*d0v,b1:Number = ypu*d1u+ypv*d1v;
		
			var c:Number = ypu*ypu+ypv*ypv;
			var n0:Number = a11*b0 - a01*b1
			var n1:Number = a00*b1 - a01*b0
			var d:Number,n:Number
			
			if(n0 + n1 <= a00*a11 - a01*a01){
				if(n0 >= 0){
					if(n1 >= 0){
						//region 0
						return 0
					}else{
						//region 5
						if(b0 > 0){
							if(b0 < a00)return c - b0 * b0 / a00
							else return a00 - 2 * b0 + c
						}else return c
					}
				}else if(n1 >= 0){
					//region 3
					if(b1 > 0){
						if(b1 < a11) return c - b1*b1/a11
						else return a11 - 2 * b1 + c
					}else return c
				}else{
					//region 4
					if(b0 < a00){
						if(b0 > 0)return c - b0*b0/a00
						else{
							if(b1 < a11){
								if(b1 > 0)return c-b1*b1/a11
								else return c
							}else return a11 - 2*b1+c
						}
					}else return a00-2*b0+c
				}
			}else if(n0 < 0){
				//region 2
				if(b1 > 0){
					if(b1 < a11)return c-b1*b1/a11
					else{
						n = a11 - a01+b0-b1
						d = a00 - 2*a01+a11
						if(n > 0){
							if(n < d)return (a11-2*b1+c)-n*n/d
							else return a00-2*b0+c
						}else return a11 - 2*b1+c
					}
				}else return c
			}else if(n1 < 0){
				//region 6
				if(b0 > 0){
					if(b0 < a00)return c-b0*b0/a00
					else{
						n = a11-a01+b0-b1
						d = a00 - 2*a01+a11
						if(n>0){
							if(n<d)return (a11-2*b1+c)-n*n/d
							else return a00-2*b0+c
						}else return a11 - 2*b1+c
					}
				}else return c
			}else{
				//region 1
				n = a11 - a01 + b0 - b1;
				d = a00 - 2*a01 + a11;
				if(n > 0){
					if(n < d)return (a11 - 2 * b1 + c) - n*n/d
					else return a00 - 2 * b0 + c
				}else return a11 - 2*b1 + c
			}
		}
	}
}

